<template>
	<n-tree class="hw-full "
		block-line
		:data="varDescriptionTree"
		:render-label="handleRenderLabel"
		default-expand-all
	/>
</template>

<script  setup lang='tsx' >
import { featchTemplateDfVar } from "@/service/api/templateManage/index"
import { TreeOption } from 'naive-ui';
import { Key } from "naive-ui/es/tree/src/interface";
import {  ref, VNodeChild } from 'vue';
import { handleCopy } from "@/utils/common/business";

const varDescriptionTree = ref<TreeOption[]>()
const field_columns = "columns";
const field_pk_columns = "pkColumn";

initVarDescriptionTree()

// function
async function initVarDescriptionTree(){
	const { data } = await featchTemplateDfVar()
	let treeOptions:TreeOption[] = []
	for(let key in data!){
		let temp:TreeOption = {
			label:data[key],key:key
		}
		if(key == field_columns){
			temp.label = key;
			let columns:Record<string,string>[] =  data[key] as Record<string,string>[]
				temp.children = []
			for(let cKey in columns[0]){
				temp.children.push({label:columns[0][cKey],key:cKey,isLeaf:true})
			}
		}
		if(key == field_pk_columns){
			temp.label = key;
			let columns:Record<string,string> =  data[key] as Record<string,string>
				temp.children = []
			for(let cKey in columns){
				temp.children.push({label:columns[cKey],key:cKey,isLeaf:true})
			}
		}
		treeOptions.push(temp)
	}
	varDescriptionTree.value = treeOptions
}

function handleRenderLabel(info: { option: TreeOption, checked: boolean, selected: boolean }):VNodeChild{

	let className = "truncate w-60px"
	const varUsage = processVarUsage(info.option.key!,info.option.isLeaf)
	return <>
		<n-tooltip trigger="hover">
			{{
				trigger:()=><>
					<n-space justify="space-between" onClick={()=>handleCopy(varUsage)}>
						<div class={className}>{info.option.key}</div>
						<div class={className + ' color-bluegray '}>{info.option.label}</div>
					</n-space>
				</>,
				default:()=><>
							{info.option.key}：{info.option.label}<br/>
						使用方法为：{varUsage}
				</>

			}}

		</n-tooltip>
	</>

}
function processVarUsage(varName: Key,isLeaf:boolean|undefined):string{
	return isLeaf ? "${column."+varName+"}" : "${"+varName+"}"
}

</script>

<style lang='scss' scoped>

</style>
